import { useState, useMemo } from 'react'
import styles from './index.module.scss'
import { calcRender } from './util'
import cm from 'classnames'
import { useEffect } from 'react'
import { useRouter } from 'next/router'

const Index = props => {
  const { pageSize = 10, className } = props
  const router = useRouter()
  const [current, setCurrent] = useState(1)
  const [init, setInit] = useState(false)
  // 计算页码排布
  const pageCodes = useMemo(() => {
    return {
      data: calcRender(current, props.total, pageSize),
      total: Math.ceil(props.total / pageSize)
    }
  }, [current, props.total])

  useEffect(() => {
    setCurrent(1)
  }, [router.asPath])

  //跳转页码
  const jump = page => {
    setCurrent(page)
  }

  useEffect(() => {
    if (!init) {
      setInit(true)
      return
    }
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
    props.onChange(current)
  }, [current])

  const renderCode = useMemo(() => {
    return pageCodes.data.split(' ').filter(item => item)
  }, [pageCodes])

  // 页码只有一页时不显示
  if (pageCodes.total <= 1) return null

  return (
    <div className={cm(styles.pagination, className)}>
      {current != 1 ? (
        <p className={cm(styles.nextPrev, styles.phoneLeft)} onClick={() => setCurrent(current - 1)}>
          上一页
        </p>
      ) : null}
      {renderCode.map((data, index) => {
        if (data == 'N') {
          return (
            <div className={styles.item} key={data + index}>
              ...
            </div>
          )
        }
        return (
          <div
            className={cm(styles.pointer, styles.item, {
              [styles.itemActive]: current == data
            })}
            key={data}
            onClick={() => jump(+data)}
          >
            {data}
          </div>
        )
      })}
      {current != pageCodes.total ? (
        <p className={cm(styles.nextPrev, styles.phoneRight)} onClick={() => setCurrent(current + 1)}>
          下一页
        </p>
      ) : null}
    </div>
  )
}

export default Index
